﻿using Quartz;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using IntelligentEscalator.BUS;
using IntelligentEscalator.Models;
using System.IO;

namespace IntelligentEscalator
{
    public class ClearLogJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                string logPath = AppDomain.CurrentDomain.BaseDirectory + "Log";
                DeleteFile(-7, logPath);
                string mqtt_logPath = AppDomain.CurrentDomain.BaseDirectory + "MqttLog";
                DeleteFile(-7, mqtt_logPath);
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
            }
        }

        public void DeleteFile(int day, string logPath)
        {
            try
            {
                if (!Directory.Exists(logPath))
                {
                    return;
                }
                DirectoryInfo folder_base = new DirectoryInfo(logPath);
                FileInfo[] files_base = folder_base.GetFiles("*.txt");  //获取.txt文件
                foreach (var file_txt in files_base)
                {
                    //获取文件创建时间
                    DateTime fileCreateTime = file_txt.CreationTime;
                    //获取当前时间
                    DateTime now = DateTime.Now.Date.AddDays(day);
                    if (fileCreateTime < now)
                    {
                        try
                        {
                            File.Delete(file_txt.FullName);
                            LogHelper.Log("删除日志" + file_txt.FullName);
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                LogHelper.Log(e.ToString());
            }
        }
    }
}
